package com.wondertek.mam.tag.wordSource.impl;

import com.wondertek.mam.tag.tagrep.TagRep;
import com.wondertek.mam.tag.wordSource.bean.NetHotWord;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 新浪词源
 * Created by wangdongxu on 2017-09-13 下午 15:35:03.
 */
public class SinaHotTodayWordSource extends WordSourceAbstract {
    private static final Logger LOGGER = LoggerFactory.getLogger(SinaHotTodayWordSource.class);

    private String urlPrefix = "http://s.weibo.com/top/summary?";
    private List<String> urlAfter;// Arrays.asList("cate=realtimehot","cate=total&key=all","cate=total&key=films","cate=total&key=person");

    public SinaHotTodayWordSource(TagRep tagRep, List<String> urlAfter) {
        super(tagRep);
        this.urlAfter = urlAfter;
    }

    @Override
    public NetHotWord getHotWordsByUrl(String url) {
        LOGGER.info("获取新浪热点:" + url);
        try{
        Proxy proxy = new Proxy(Proxy.Type.HTTP,new InetSocketAddress("192.168.1.39",3128));
        Document doc = Jsoup.connect(url).proxy(proxy).get();
        //Document doc = Jsoup.connect(url).get();
        String script = doc.getElementsByTag("script").get(14).html();
        String substring = script.substring(script.indexOf("\"html\":\"")+8, script.indexOf("\"}"));
        String[] split = substring.split("(list_person\\\\\">)|(list_films\\\\\">)|(list_all\\\\\">)|(list_realtimehot\\\\\">)|(ad_hotword_realtime_[0-9]*\\\\\"\\\\n>)");
        List<String> splitList = new ArrayList<>();
        for (int i = 0; i < split.length; i++) {
            if (i%2==1) splitList.add(split[i]);
        }
            Map<String, Boolean> collect = splitList.stream()
                .map(s -> decodeUnicode(s.split("<\\\\/a>")[0]))
                .collect(Collectors.toMap(key -> key, value -> true));
            return new NetHotWord("新浪热搜",collect);
        } catch (IOException e) {
            LOGGER.error("获取新浪热点出现错误:"+url);
    }
        return null;
    }

    @Override
    public List<String> getUrls(){
        return urlAfter
            .parallelStream()
            .map(p -> urlPrefix + p)
            .collect(Collectors.toList());
    }

    //Unicode转中文
    public static String decodeUnicode( String dataStr) {
        int start = dataStr.indexOf("\\u");
        while (start !=-1){
            String subStr = dataStr.substring(start + 2, start + 6);
            char letter = (char) Integer.parseInt(subStr, 16);
            dataStr = dataStr.replaceAll("\\\\u"+subStr, String.valueOf(letter));
            start = dataStr.indexOf("\\u");
        }
        return dataStr;

    }

}
